<template>
	<BasePopup v-model="localIsShow" :titleT="localItem.title" titleIcon="discover2">
		<div class="w-full flex flex-col items-center p-[20px] gap-4">
			<div class="w-[65px]">
				<base-image
					:src="'activity/reward/' + localItem.icon"
					class="inset-0 w-full h-full rounded-lg" />
			</div>
			<div class="flex flex-col items-center justify-center">
				<div style="font-size: 18px">{{ localItem.title }}</div>
				<div style="margin-top: 4px; color: #adb0b7">{{ localItem.content }}</div>
			</div>
			<div class="w-full" v-if="localItem.status === 1">
				<div
					v-for="item in moneyList"
					:key="item.label"
					class="flex justify-between h-[45px] m-4"
					style="border-radius: 8px; background: #2a364b; padding: 8px 16px 8px 16px">
					<div class="flex items-center">
						<!-- <base-image :src="'activity/reward/' + item.icon" class="w-[14px]" /> -->
						<base-currency v-if="item.label" :currency="item.label" class="w-[14px]" />
						<span class="ml-1" style="font-size: 14px">{{ item.label }}</span>
					</div>
					<div class="flex items-center">{{ item.value }}</div>
				</div>
			</div>
			<div v-if="localItem.status === 2">{{ t('activity.moneyPopup.noRebates') }}</div>
			<div v-if="localItem.status === 3 || localItem.status === 4" class="w-full m-4">
				<base-dropdown
					v-model="selectedCurrency"
					v-model:item="selectedCurrencyItem"
					:default-value="walletStore.balanceCur?.currency"
					ref="dropdownCurrencyRef"
					:options="walletStore.balanceList.map((i) => ({ ...i, id: i.currency }))"
					filterable
					filter-field="appName"
					min-width="trigger"
					immediate>
					<template #default="{ data, show }">
						<div class="flex items-center gap-1 h-12 px-3 rounded-lg bg-bg-2">
							<base-currency v-if="data" :currency="data?.currency" />
							<div>{{ data?.appName || data?.currency }}</div>
							<base-amount
								:value="data?.freeAmount"
								:currency="data?.currency"
								hide-currency
								class="flex-auto w-[1px] text-right text-t-2" />
							<base-icon
								name="down"
								class="ml-auto text-t-3 text-[20px] duration-300"
								:class="{ 'rotate-180': show }" />
						</div>
					</template>
					<template #content="{ item }">
						<div class="flex items-center w-full gap-1 h-12">
							<base-currency :currency="item?.currency" />
							<div>{{ item?.appName || item?.currency }}</div>
							<base-amount
								:value="item?.freeAmount"
								:currency="item?.currency"
								hide-currency
								class="flex-auto w-[1px] text-right text-t-2" />
							<div class="w-5">
								<base-icon
									v-if="item.id === selectedCurrency"
									name="tick"
									class="text-t-1"
									size="20" />
							</div>
						</div>
					</template>
				</base-dropdown>
			</div>
			<div class="flex justify-center items-center gap-1">
				<base-image src="activity/reward/d.png" class="w-[14px]" />
				<span>{{ localItem.money }}</span>
			</div>
			<div v-if="localItem.status === 3" class="flex justify-around" style="width: 100%">
				<div
					v-for="item in timeList"
					:key="item.label"
					class="w-[80px] h-[80px] flex flex-col items-center justify-center"
					style="background: #131a27; border-radius: 8px">
					<div style="font-size: 20px">{{ item.value }}</div>
					<div style="font-size: 12px">{{ item.label }}</div>
				</div>
			</div>

			<div style="padding: 8px 16px 8px 16px" class="w-full">
				<n-button
					@click="receive"
					:disabled="+localItem.money <= 0"
					:loading="loading"
					class="w-full h-[48px]"
					type="primary"
					style="border-radius: 25px; color: white">
					{{ t('activity.moneyPopup.claim') }}
				</n-button>
			</div>
			<div v-if="localItem.bonusStatus !== 0" style="font-size: 12px">
				{{ t('activity.moneyPopup.expireTime', { time: localItem.expiredAt }) }}
			</div>
		</div>
	</BasePopup>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted, computed } from 'vue'
import { BaseDropdown, BaseIcon, BaseImage, BaseAmount, BaseCurrency } from '@/components/base'
import { useWalletStore } from '@/store'
import { BalanceItem } from '@/types'

import { CurrencyEnum } from '@/enums'
import { putRedeem } from '@/api/activity'
import { useMessage } from '@/hooks'
import { t } from '@/utils'
import BasePopup from '@/components/base/popup/index.vue'
// 定义接收的 props
const props = defineProps({
	isShow: { type: Boolean, default: false },
	current: { type: Object, required: true },
	onClick: { type: Function, required: true }
})

// 定义 emit 事件
const emit = defineEmits(['update:isShow'])

// 定义本地响应式变量
const localIsShow = ref(false)
const localItem = ref<any>({})
// 同步父组件的值到本地状态
watch(
	() => props.isShow,
	(newVal) => {
		localIsShow.value = newVal
	}
)
watch(
	() => props.current,
	(newVal) => {
		localItem.value = newVal
	}
)
// 当本地状态变化时，通知父组件
watch(
	() => localIsShow.value,
	(newVal) => {
		emit('update:isShow', newVal)
	}
)
const loading = ref(false)
const receive = async () => {
	const message = useMessage()
	loading.value = true
	try {
		await putRedeem({
			id: localItem.value.id,
			userId: localItem.value.userId,
			currency: selectedCurrency.value
		})
		message.success(t('activity.moneyPopup.claimSuccess'))
		localIsShow.value = false
		props.onClick()
	} catch (error) {
		message.error(error)
	} finally {
		loading.value = false
	}
}
const moneyList = computed(() => {
	const bonusAmount = props.current?.bonusAmountCurrency || {}
	return Object.entries(bonusAmount).map(([currency, amount]) => ({
		label: currency,
		value: amount,
		icon: `${currency.toLowerCase()}.png`
	}))
})
const timer = ref<number>()
const timeList = ref([
	{ label: 'Day', value: 0 },
	{ label: 'Hour', value: 0 },
	{ label: 'Min', value: 0 },
	{ label: 'Sec', value: 0 }
])

const updateTime = () => {
	// 检查是否有有效的过期时间
	if (!props.current?.expiredAt) {
		timeList.value.forEach((item) => (item.value = 0))
		return
	}

	const now = new Date()
	const receiveTime = new Date(props.current.expiredAt)
	const diff = receiveTime.getTime() - now.getTime()

	if (diff <= 0 || isNaN(diff)) {
		timeList.value.forEach((item: any) => (item.value = 0))
		clearInterval(timer.value)
		localItem.value.status = 4
		return
	}

	// 使用 Math.max 确保不会出现负数，使用 || 0 防止 NaN
	timeList.value[0].value = Math.max(0, Math.floor(diff / (1000 * 60 * 60 * 24))) || 0
	timeList.value[1].value =
		Math.max(0, Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))) || 0
	timeList.value[2].value = Math.max(0, Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))) || 0
	timeList.value[3].value = Math.max(0, Math.floor((diff % (1000 * 60)) / 1000)) || 0
}

onMounted(() => {
	if (props.current.bonusStatus !== 0) {
		updateTime()
		timer.value = setInterval(updateTime, 1000)
	}
})

onUnmounted(() => {
	if (timer.value) {
		clearInterval(timer.value)
	}
})

const walletStore = useWalletStore()
const selectedCurrency = ref<CurrencyEnum | ''>('')
const selectedCurrencyItem = ref<BalanceItem>()
</script>
<style scoped lang="scss">
:deep(.n-button--disabled) {
	background-color: #2d3648;
	border: none;

	* {
		border: none !important;
	}
}
</style>
